"use client"

import { useState, useEffect } from 'react'
import { cn } from "@/lib/utils"
import Link from 'next/link'
import { UserCircle, Home, Settings, BarChart2, Moon, Sun, LogOut, Users, MapPin, Medal } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useTheme } from "next-themes"
import { Toaster } from '@/components/ui/toaster'
import { usePathname } from 'next/navigation'

export default function AdminLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const { theme, setTheme } = useTheme()
  const [mounted, setMounted] = useState(false)
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const pathname = usePathname()

  // 避免服务器端渲染和客户端渲染不匹配
  useEffect(() => {
    setMounted(true)

    // 检查认证状态
    const sessionAuth = sessionStorage.getItem('admin_auth')
    const localAuth = localStorage.getItem('admin_auth')
    if (sessionAuth || localAuth) {
      setIsAuthenticated(true)
    }
  }, [])

  // 监听存储事件，保持认证状态同步
  useEffect(() => {
    const handleStorageChange = () => {
      const sessionAuth = sessionStorage.getItem('admin_auth')
      const localAuth = localStorage.getItem('admin_auth')
      setIsAuthenticated(sessionAuth !== null || localAuth !== null)
    }

    window.addEventListener('storage', handleStorageChange)
    return () => {
      window.removeEventListener('storage', handleStorageChange)
    }
  }, [])

  // 如果还没有加载完毕或者未认证，仅渲染children
  if (!mounted || !isAuthenticated) {
    return (
      <>
        {children}
        <Toaster />
      </>
    )
  }

  // 已认证，显示完整布局
  return (
    <div className="h-screen flex flex-col bg-[#0c0f14] text-white">
      {/* 顶部导航栏 */}
      <header className="border-b border-gray-800 bg-[#0f131a] px-4 py-3 flex items-center justify-between">
        <div className="flex items-center space-x-2">
          <div className="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center">
            <Settings className="h-5 w-5" />
          </div>
          <h1 className="text-xl font-bold">Tooth Meter</h1>
        </div>
        
        <div className="flex items-center space-x-4">
          {mounted && (
            <Button
              variant="ghost"
              size="icon"
              className="rounded-full"
              onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
            >
              {theme === 'dark' ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
            </Button>
          )}
          
          <Link href="/" className="flex items-center space-x-1 px-3 py-1.5 rounded-lg hover:bg-blue-700 transition-colors border border-blue-700 text-sm">
            <Home className="h-4 w-4" />
            <span>返回首页</span>
          </Link>
          
          <div className="flex items-center space-x-2">
            <div className="w-8 h-8 rounded-full bg-blue-800 flex items-center justify-center">
              <UserCircle className="h-5 w-5" />
            </div>
            <span className="text-sm font-medium">管理员</span>
          </div>
        </div>
      </header>
      
      <div className="flex flex-1 overflow-hidden">
        {/* 侧边导航栏 */}
        <aside className="w-16 md:w-64 bg-[#0f131a] border-r border-gray-800 flex flex-col">
          <nav className="flex flex-col p-2 space-y-1 flex-1">
            <Link 
              href="/admin" 
              className={cn(
                "flex items-center space-x-3 px-3 py-2 rounded-lg transition-colors",
                pathname === '/admin' 
                  ? "bg-blue-900/50 text-blue-300" 
                  : "hover:bg-[#1a1d24] text-gray-400 hover:text-gray-300"
              )}
            >
              <BarChart2 className="h-5 w-5 min-w-5" />
              <span className="hidden md:inline">控制面板</span>
            </Link>
            
            <Link 
              href="/admin/players" 
              className={cn(
                "flex items-center space-x-3 px-3 py-2 rounded-lg transition-colors",
                pathname === '/admin/players' 
                  ? "bg-blue-900/50 text-blue-300" 
                  : "hover:bg-[#1a1d24] text-gray-400 hover:text-gray-300"
              )}
            >
              <Users className="h-5 w-5 min-w-5" />
              <span className="hidden md:inline">玩家管理</span>
            </Link>
            
            <Link 
              href="/admin/tiers" 
              className={cn(
                "flex items-center space-x-3 px-3 py-2 rounded-lg transition-colors",
                pathname === '/admin/tiers' 
                  ? "bg-blue-900/50 text-blue-300" 
                  : "hover:bg-[#1a1d24] text-gray-400 hover:text-gray-300"
              )}
            >
              <Medal className="h-5 w-5 min-w-5" />
              <span className="hidden md:inline">段位管理</span>
            </Link>
            
            <Link 
              href="/admin/regions" 
              className={cn(
                "flex items-center space-x-3 px-3 py-2 rounded-lg transition-colors",
                pathname === '/admin/regions' 
                  ? "bg-blue-900/50 text-blue-300" 
                  : "hover:bg-[#1a1d24] text-gray-400 hover:text-gray-300"
              )}
            >
              <MapPin className="h-5 w-5 min-w-5" />
              <span className="hidden md:inline">地区管理</span>
            </Link>
            
            <Link 
              href="/admin/settings" 
              className={cn(
                "flex items-center space-x-3 px-3 py-2 rounded-lg transition-colors",
                pathname === '/admin/settings' 
                  ? "bg-blue-900/50 text-blue-300" 
                  : "hover:bg-[#1a1d24] text-gray-400 hover:text-gray-300"
              )}
            >
              <Settings className="h-5 w-5 min-w-5" />
              <span className="hidden md:inline">系统设置</span>
            </Link>
          </nav>
          
          <div className="p-2 mt-auto border-t border-gray-800">
            <button 
              className="w-full flex items-center space-x-3 px-3 py-2 rounded-lg transition-colors hover:bg-red-900/20 text-red-400 hover:text-red-300"
              onClick={() => {
                sessionStorage.removeItem('admin_auth')
                localStorage.removeItem('admin_auth')
                setIsAuthenticated(false)
                window.location.reload() // 强制刷新页面
              }}
            >
              <LogOut className="h-5 w-5 min-w-5" />
              <span className="hidden md:inline">退出登录</span>
            </button>
          </div>
        </aside>
        
        {/* 主内容区域 */}
        <main className="flex-1 overflow-auto p-6">
          {children}
        </main>
      </div>
      
      {/* 全局通知组件 */}
      <Toaster />
    </div>
  )
} 